<template>
  <div class="home">
    <Hero />
    <div class="content-layout">
      <main class="home-main-content">
        <Carousel v-if="carouselSlides?.length > 0" :slides="carouselSlides" @click="goToPost" />
        <MomentsList />

        <section class="posts-section" aria-labelledby="latest-articles-heading" ref="postsSection">
          <div class="section-title-wrapper">
            <h2 id="latest-articles-heading" class="section-title">
              <i class="el-icon-reading"></i>
              最新文章
              <div class="title-decoration"></div>
            </h2>
            <p class="section-subtitle">探索发现值得阅读的技术内容</p>
          </div>
          <el-tabs v-model="activeName" @tab-click="handleClick" class="category-tabs">
            <el-tab-pane v-for="category in categories" :key="category.id" :name="String(category.id)">
              <template slot="label">
                <span class="label-info">
                  <i :class="category.icon"></i>
                  {{ category.name }}
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
          <ArticleList :articles="articleList" :loading="loading" :total="total" :params="params"
            @article-click="goToPost" @page-change="changePage" @category-click="switchCategory" class="article-list" />
        </section>
      </main>
      <Sidebar />
    </div>
  </div>
</template>

<script>
import ArticleList from "@/components/ArticleList/index.vue";
import Carousel from "@/views/home/components/carousel.vue";
import Sidebar from "@/components/Sidebar/index.vue";
import MomentsList from "@/views/home/components/moments.vue";
import Hero from "@/components/Hero/index.vue";
import {
  getArticlesApi,
  getCarouselArticlesApi,
  getAllCategoriesApi,
} from "@/api/article";

export default {
  name: "Home",
  metaInfo() {
    return {
      title: "首页 | 探索技术与创意的交汇点 - 🎯 KingCola-ICG Blog | 始于代码，不止于代码 ",
      meta: [
        {
          name: "description",
          content:
            "欢迎来到KingCola-ICG的个人博客。在这里，我分享关于前端开发、软件工程、技术教程以及个人生活感悟。探索Vue、React、Node.js等最新技术，共同成长。",
        },
        {
          name: "keywords",
          content:
            "KingCola-ICG, 博客, 技术博客, 前端开发, Vue, React, Node.js, JavaScript, 技术分享, 个人成长, 生活记录",
        },
      ],
    };
  },
  components: {
    ArticleList,
    Carousel,
    Sidebar,
    MomentsList,
    Hero,
  },
  data() {
    return {
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      articleList: [],
      carouselSlides: [],
      loading: false,
      activeName: "all",
      categories: [
        {
          id: "all",
          name: "全部",
          icon: "el-icon-menu",
        },
      ],
    };
  },
  methods: {
    /**
     * 统一的分类切换处理方法
     * @param {number|null} categoryId 新的分类ID，null代表"全部"
     */
    _updateCategory(categoryId) {
      const normalizedId = categoryId === null ? null : Number(categoryId);
      if (this.params.categoryId === normalizedId) return;

      this.activeName = normalizedId === null ? 'all' : String(normalizedId);
      this.params.categoryId = normalizedId;
      this.params.pageNum = 1;
      this.getArticleList();
    },

    /**
     * 处理 Element UI 标签页的点击事件
     * @param {object} tab 标签页实例
     */
    handleClick(tab) {
      const categoryId = tab.name === 'all' ? null : Number(tab.name);
      this._updateCategory(categoryId);
    },

    /**
     * 跳转到文章详情
     * @param {number} id 文章id
     */
    goToPost(id) {
      this.$router.push(`/post/${id}`);
    },
    /**
     * 切换页码
     * @param {number} page 页码
     */
    changePage(page) {
      this.params.pageNum = page;
      this.getArticleList();
      window.scrollTo({
        top: this.$refs.postsSection?.offsetTop - 80,
        behavior: "smooth",
      });
    },
    /**
     * 从文章列表组件内部切换分类
     * @param {string} categoryName 分类名称
     */
    switchCategory(categoryName) {
      if (!categoryName) return;

      const category = this.categories.find(cat => cat.name === categoryName);

      if (category && category.id) {
        const categoryId = category.id === 'all' ? null : category.id;
        this._updateCategory(categoryId);

        // 平滑滚动到标签栏
        this.$nextTick(() => {
          const tabsEl = document.querySelector('.el-tabs__header');
          if (tabsEl) {
            tabsEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        });
      } else {
        console.error(`Category with name "${categoryName}" not found.`);
      }
    },
    /**
     * 获取文章列表
     */
    getArticleList() {
      this.loading = true;
      getArticlesApi(this.params)
        .then((res) => {
          this.articleList = res.data.records;
          this.total = res.data.total;
        })
        .catch((error) => {
          console.error("Failed to fetch articles:", error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 获取轮播和推荐文章
     */
    getCarouselArticles() {
      getCarouselArticlesApi().then((res) => {
        this.carouselSlides = res.data;
      });
    },
    /**
     * 获取所有分类
     */
    getAllCategories() {
      getAllCategoriesApi().then((res) => {
        const icons = [
          "el-icon-document",
          "el-icon-collection",
          "el-icon-reading",
          "el-icon-coffee-cup",
          "el-icon-notebook-2",
          "el-icon-edit",
        ];
        const categoriesWithIcons = res.data.map((category) => ({
          ...category,
          icon: icons[Math.floor(Math.random() * icons.length)],
        }));
        this.categories.push(...categoriesWithIcons);
      });
    },
  },
  created() {
    this.getArticleList();
    this.getCarouselArticles();
    this.getAllCategories();
  },
};
</script>

<style lang="scss" scoped>
@use 'sass:color';
@use '@/styles/variables.scss' as *;
@use '@/styles/mixins.scss' as *;

.home {
  width: 100%;
}

.posts-section {
  margin-top: 2rem;
  color: var(--text-color-primary);
  position: relative;
}

.section-title-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 1.5rem;
  position: relative;
}

.section-title {
  font-size: 1.8rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  text-align: center;
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  color: var(--text-primary);

  i {
    color: $primary;
    font-size: 1.6rem;
  }

  .title-decoration {
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 80px;
    height: 3px;
    background: linear-gradient(to right, $primary, color.adjust($primary, $lightness: 15%));
    border-radius: 3px;
  }
}

.section-subtitle {
  color: var(--text-secondary);
  font-size: 1rem;
  margin-top: 0.5rem;
  margin-bottom: 1.5rem;
}

.category-tabs {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: var(--border-color);
    z-index: 0;
  }
}

.content-layout {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px;
  gap: $spacing-lg * 2;
  padding: $spacing-lg;
  margin-bottom: $spacing-xl * 2;
  min-height: calc(100vh - 80px);
  align-items: start;

  @include responsive(lg) {
    grid-template-columns: 1fr;
    padding: $spacing-sm;
  }
}

.home-main-content {
  min-width: 0;
  width: 100%;
  height: 100%;

  .carousel {
    margin-bottom: $spacing-xl;
    width: 100%;
    max-height: 480px;

    @include responsive(md) {
      margin-bottom: $spacing-xl;
      max-height: 280px;

      :deep(h3) {
        font-size: 1.2em;
      }
    }
  }
}

:deep(.el-tabs__nav-scroll) {
  overflow-x: scroll !important;

  &::-webkit-scrollbar {
    display: none !important;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.label-info {
  display: flex;
  align-items: center;
  gap: $spacing-base;
  color: var(--text-primary);
  // .el-icon{
  //   margin-right: 4px;
  //   vertical-align: middle;
  // }
}
</style>
